import React, { useState, useEffect } from 'react';
import { Table, Input, Button, message, Modal, Form } from 'antd';
import { getConceptDataList, conceptInsert, conceptUpdate, conceptDelete, getAllConceptNames } from '../../service/concept-service';
import useUserStore from '../../store/userStore';

const ConceptPage = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [name, setName] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingRecord, setEditingRecord] = useState(null);
  const setConceptNames = useUserStore((state) => state.setConceptNames);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '定义',
      dataIndex: 'definition',
      key: 'definition',
    },
    {
      title: '扩展属性',
      dataIndex: 'feature',
      key: 'feature',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button type="link" onClick={() => showEditModal(record)}>
            编辑
          </Button>
          <Button type="link" danger onClick={() => confirmDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  const fetchData = async () => {
    setLoading(true);
    try {
      const params = {
        currentPage, 
        pageSize,
        name: name ? name : undefined
      }
      const response = await getConceptDataList({ ...params });
      const { tableData=[], paging={}} = response.data;
      setData(tableData);
      setTotal(paging.totalCount);
    } catch (err) {
      message.error(err.errorMsg || '查询失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchConceptNames = async () => {
    setLoading(true);
    try {
 
      const response = await getAllConceptNames({});
      console.log('names', response)
      setConceptNames(response.data || {})
    } catch (err) {
      message.error(err.errorMsg || '查询失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    fetchConceptNames();
  }, [currentPage, pageSize]);

  const handleSearch = () => {
    setCurrentPage(1);
    fetchData();
  };

  const showAddModal = () => {
    setEditingRecord(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const showEditModal = (record) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingRecord) {
        // 编辑模式
        await conceptUpdate({ ...editingRecord, ...values });
        message.success('概念更新成功！');
      } else {
        // 新增模式
        await conceptInsert(values);
        message.success('概念添加成功！');
      }
      setIsModalVisible(false);
      fetchData(); // 刷新数据
    } catch (err) {
      message.error(err.errorMsg || '操作失败');
    }
  };

  const confirmDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除概念 "${record.name}" 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await conceptDelete({
            id: record.id
          });
          message.success('概念删除成功！');
          fetchData(); // 刷新数据
        } catch (err) {
          message.error(err.errorMsg || '删除概念失败。');
        }
      },
    });
  };

  return (
    <div style={{ paging: '20px' }}>
      <Input
        placeholder="请输入名称"
        value={name}
        onChange={(e) => setName(e.target.value)}
        style={{ width: 200, marginRight: 10 }}
      />
      <Button type="primary" onClick={handleSearch} style={{ marginRight: 10 }}>
        查询
      </Button>
      <Button type="primary" onClick={showAddModal}>
        增加
      </Button>
      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          onChange: (page, pageSize) => {
            setCurrentPage(page);
            setPageSize(pageSize);
          },
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'], // Set pagination position to bottom right
          showTotal: (total) => `总数: ${total}`, // Display total count in pagination
        }}
        style={{ marginTop: 20 }}
      />
      <Modal
        title={editingRecord ? "编辑概念" : "添加新概念"}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: '请输入名称！' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="definition"
            label="定义"
            rules={[{ required: true, message: '请输入定义！' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ConceptPage;